<template>
  <ElUpload
    ref="upload"
    :class="{ disabled: uploadDisabled }"
    :action="`${adminService}sys-file/upload`"
    :headers="headers"
    list-type="picture-card"
    :multiple="true"
    :auto-upload="true"
    :file-list="fileList"
    :data="uploadData"
    :limit="limit"
    :on-change="handleChange"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <template #default>
      <i class="el-icon-plus"></i>
    </template>
    <template #file="{ file }">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <!--        <span
            v-if="uploadDisabled"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>-->
          <span v-if="uploadDisabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </template>
    <template #tip>
      <div class="el-upload__tip">
        只能上传.png, .jpg, .JPG, .JPEG, .jpeg, .PNG .GIF, .gif文件，且不超过{{ fileSize }}M
      </div>
    </template>

    <ElementDialog title="查看图片" :visible.sync="dialogVisible">
      <img width="100%;height: 100%;" :src="dialogImageUrl" alt="" />
    </ElementDialog>
  </ElUpload>
</template>

<script>
  import { services } from '@/config'
  import { getHeader } from '@/api/attachment/attachment'
  import { delObj, fetchList } from '@/api/admin/sys-file'

  export default {
    name: 'UploadAvatar',
    props: {
      /* 上传参数 */
      data: {
        type: Object,
        uniqueCode: { type: String, default: '' },
        asset: { type: String, default: '' },
        photo: { type: String, default: '' },
        classify: { type: String, default: '' }
      },
      /* 组件参数 */
      limit: { type: Number, default: 1 },
      fileSize: { type: Number, default: 2 }
    },
    data() {
      return {
        headers: {},
        uploadData: this.data,
        dialogImageUrl: '',
        dialogVisible: false,
        fileObj: {},
        fileList: [],
        adminService: services.adminService,
        uploadDisabled: false
      }
    },
    created() {
      this.headers = getHeader()
      this.init()
    },
    methods: {
      async init() {
        const res = await fetchList({ uniqueCode: this.data.uniqueCode })
        if (res.data.data.records.length > 0) {
          this.fileObj = res.data.data.records[0]
          const url = `/admin/sys-file/${this.fileObj.bucketName}/${this.fileObj.fileName}`
          this.fileList = [{ url }]
        } else {
          if (!this.$isBlank(this.data.photo)) {
            this.fileList = [{ url: this.data.photo }]
          }
        }
        this.initPicture()
      },
      handleAvatarSuccess(res, file) {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.fileList.push(res.data)
        const formImgList = []
        this.fileList.forEach(item => {
          formImgList.push({
            name: item.fileName,
            url: item.url
          })
        })
        this.fileObj = res.data.sysFile
        this.$emit('uploadSuccess', res.data)
      },
      beforeAvatarUpload(file) {
        const imgFormat = 'IMAGE/PNG,IMAGE/JPG,IMAGE/JPEG,IMAGE/PNG,IMAGE/GIF'
        const isJPG = imgFormat.includes((file.raw ? file.raw.type : file.type).toUpperCase())
        const isLtxM = file.size / 1024 / 1024 < this.fileSize

        if (!isJPG) {
          this.$message.error('上传图片只能是 .JPG .JPEG .PNG .GIF 格式!')
        }

        if (!isLtxM) {
          this.$message.error(`上传头像图片大小不能超过${this.fileSize}MB!`)
        }
        return isJPG && isLtxM
      },
      handleRemove(file) {
        if (this.fileObj.id) {
          delObj(this.fileObj.id)
          this.$emit('uploadDel')
        }
        this.fileList = []
        this.initPicture()
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleDownload(file) {
        this.$downBlobFile(
          `/admin/sys-file/${this.fileObj.bucketName}/${this.fileObj.fileName}`,
          {},
          this.fileObj.fileName
        )
      },
      // 上传图片
      handleChange(file, fileList) {
        const isFileType = this.beforeAvatarUpload(file)
        // 如果文件类型不对，则清空表单及附件列表
        if (!isFileType) {
          this.fileList = []
          return
        }
        // this.inputForm.img = file.raw // 这个就是咱们上传图片的二进制对象
        this.fileList = fileList
        this.initPicture()
      },
      initPicture() {
        if (this.fileList.length >= this.limit) {
          this.uploadDisabled = true
        } else {
          this.uploadDisabled = false
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .disabled .el-upload--picture-card {
    display: none;
  }

  ::v-deep .el-upload-list__item.is-ready {
    display: none;
  }
</style>
